import { defineStore } from 'pinia'
import { ref, computed } from 'vue'

export const useSceneStore = defineStore('scene', () => {
  // 从localStorage恢复场景状态
  const getStoredScene = () => {
    try {
      const stored = localStorage.getItem('currentScene')
      return stored ? JSON.parse(stored) : null
    } catch (error) {
      console.error('恢复场景状态失败:', error)
      return null
    }
  }
  
  // 当前选中的场景
  const currentScene = ref(getStoredScene())
  
  // 设置当前场景
  const setCurrentScene = (scene) => {
    currentScene.value = scene
    // 保存到localStorage
    try {
      localStorage.setItem('currentScene', JSON.stringify(scene))
    } catch (error) {
      console.error('保存场景状态失败:', error)
    }
  }
  
  // 获取当前场景背景图片URL
  const currentSceneBackgroundUrl = computed(() => {
    if (currentScene.value && currentScene.value.sceneImageUrl) {
      // 如果场景有多个图片，取第一个作为背景
      const urls = currentScene.value.sceneImageUrl.split(';')
      return urls[0]
    }
    // 默认背景图片
    return 'https://fastcdn.mihoyo.com/content-v2/bh3/122055/7998a558197631b0d4db3ecf71d6d578_3092415518577911493.jpg'
  })
  
  // 清除当前场景
  const clearCurrentScene = () => {
    currentScene.value = null
    // 清除localStorage
    try {
      localStorage.removeItem('currentScene')
    } catch (error) {
      console.error('清除场景状态失败:', error)
    }
  }
  
  return {
    currentScene,
    currentSceneBackgroundUrl,
    setCurrentScene,
    clearCurrentScene
  }
})